<template>
  <el-row class="user-info-form add-property-detail" type="flex" justify="center">
    <el-col class="asset-info-form">
      <el-form
        label-width="150px"
        :model="assetInfoForm"
        :rules="assetInfoFormRules"
        ref="assetInfoForm"
        @submit.native.prevent
      >
        <input type="hidden" v-model="assetInfoForm.id" />
        <el-form-item label="图片：" prop="pictures">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="false"
            ref="upload"
            list-type="picture-card"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemovePic"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :on-preview="$imgPreview"
            :file-list="qiniuData.fileList"
            :limit="1"
            :on-exceed="handleExceed"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称：" prop="name">
          <el-input v-model="assetInfoForm.name" auto-complete="off" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="assetInfoForm.status">
            <el-radio label="0">在用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="系统与类别：" prop="categoryId">
          <tree-select
            v-model="assetInfoForm.categoryId"
            filterable
            :data="typeList"
            :defaultProps="typeDefaultProps"
            :checkedKeys="defaultCheckedCategoryId"
            :nodeKey="typeNodeKey"
          ></tree-select>
        </el-form-item>
        <el-form-item label="所在建筑物：" prop="fbsId">
          <tree-select
            class="asset-build"
            v-model="assetInfoForm.fbsId"
            filterable
            :data="newBuildList"
            :defaultProps="buildDefaultProps"
            :checkedKeys="defaultCheckedFbsId"
            @node-click="handleNodeClick"
            :nodeKey="buildNodeKey"
          ></tree-select>
          <span v-show="isChooseTree" class="color-7">*注意：请确保您所选择的资产务必挂在楼层及楼层以下。</span>
        </el-form-item>
        <el-form-item label="具体位置：" prop="location">
          <el-input v-model="assetInfoForm.location" auto-complete="off" placeholder="请输入具体位置"></el-input>
        </el-form-item>
        <el-form-item label="标识类型：" prop="visualCodeType">
          <el-row>
            <el-radio :disabled="isEdit" v-model="assetInfoForm.visualCodeType" label="0">单点型-由系统自动生成二维码</el-radio>
          </el-row>
          <el-row>
            <el-radio :disabled="isEdit" v-model="assetInfoForm.visualCodeType" label="1">单点型-人工添加二维码编码</el-radio>
            <el-input
              :disabled="isEdit"
              v-if="assetInfoForm.visualCodeType==1"
              v-model="assetInfoForm.visualCode"
              auto-complete="off"
              placeholder="请输入二维码编码"
            ></el-input>
          </el-row>
          <el-row>
            <el-radio :disabled="isEdit" v-model="assetInfoForm.visualCodeType" label="2">区域型</el-radio>
          </el-row>
        </el-form-item>
        <el-form-item label="维保公司：" prop="maintainCompanyType">
          <el-row>
            <el-radio v-model="assetInfoForm.maintainCompanyType" label="1">由单位的维保公司维保</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="assetInfoForm.maintainCompanyType" label="0">其他公司</el-radio>
            <!-- <el-select v-if="assetInfoForm.maintainCompanyType == 1" v-model="assetInfoForm.maintainCompanyId" placeholder="请选择维保公司">
                            <el-option
                                v-for="item in maintainCompanyOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
            </el-select>-->
          </el-row>
        </el-form-item>
        <el-form-item label="编号：" prop="serialNumber">
          <el-input v-model="assetInfoForm.serialNumber" auto-complete="off" placeholder="请输入编号"></el-input>
        </el-form-item>
        <el-form-item label="型号：" prop="model">
          <el-input v-model="assetInfoForm.model" auto-complete="off" placeholder="请输入型号"></el-input>
        </el-form-item>
        <el-form-item label="品牌：" prop="brand">
          <el-input v-model="assetInfoForm.brand" auto-complete="off" placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="生产厂家：" prop="producerName">
          <el-input v-model="assetInfoForm.producerName" auto-complete="off" placeholder="请输入生产厂家名称"></el-input>
        </el-form-item>
        <el-form-item label="生产日期：" prop="productionTimeStr">
          <el-date-picker
            v-model="assetInfoForm.productionTimeStr"
            type="date"
            placeholder="选择日期时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item v-show="assetInfoForm.productionTimeStr" label="保质期：">
          <el-input-number v-model="assetInfoForm.yearNum" size="medium" :precision="0" :min="0" style="width: 110px"></el-input-number>
          <span>&nbsp;年</span>
          <!-- <el-input-number
            v-model="assetInfoForm.monthNum"
            size="medium"
            :precision="0"
            :min="0"
            style="width: 110px"
          ></el-input-number>
          <span>月</span>
          <el-input-number
            v-model="assetInfoForm.dayNum"
            size="medium"
            :precision="0"
            :min="0"
            style="width: 110px"
          ></el-input-number>
          <span>日</span>-->
        </el-form-item>
        <el-form-item label="关联物联设备：" prop="relateFcIds" id="relateFcIds">
          <el-select
            multiple
            v-model="assetInfoForm.relateFcIds"
            placeholder="请选择关联物联设备"
            filterable
            :filter-method="getFcfOptions"
            :loading="relateFcIdsSelectloading"
          >
            <el-option v-for="item in relateFcOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            <el-pagination
              @current-change="handleCurrentChange"
              small
              :current-page.sync="relateFcPageIndex"
              layout="total, prev, pager, next"
              :total="relateFcTotal"
            ></el-pagination>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="remarks">
          <el-input type="textarea" v-model="assetInfoForm.remarks" auto-complete="off" placeholder="添加资产的单独信息"></el-input>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click.stop="closeAssetInfo" round>取消</el-button>
          <el-button type="primary" @click="saveAsset('assetInfoForm',1)" round>保存</el-button>
          <el-button
            v-show="isAddWrite"
            v-if="isContinue"
            type="primary"
            @click="saveAsset('assetInfoForm',2)"
            round
          >保存并继续添加</el-button>
          <el-button
            v-show="isAddWrite"
            type="primary"
            @click="saveAsset('assetInfoForm',3)"
            round
          >快速复制</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-dialog
      :close-on-click-modal="false"
      title="快速复制"
      width="600px"
      top="10vh"
      :visible.sync="copyDialogVisible"
      v-dialogDrag
      append-to-body
    >
      <el-form>
        <el-form-item label="复制数量：" label-width="200px">
          <el-input-number
            v-model="copyNum"
            size="medium"
            :precision="0"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <div style="padding-left:150px;">
          <div><span style="color:red;">*</span>提示：</div>
          <div>1、复制的资产，信息将完全一致</div>
          <div>2、复制数量已包括当前创建的资产 </div>
        </div>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click.stop="copyDialogVisible=false" round>取消</el-button>
          <el-button type="primary" @click="confirmCopy" round>保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-row>
</template>

<script>
import { qnToken } from '@/api/api'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getAssetsCategoryId, updateAInfo,batchSaveAssetsInfo } from '@/api/assets'
import { getFcfSelectList } from '@/api/fcf'
import util from '@/utils/util'

export default {
  name: 'AssetInfoForm',
  components: {
    TreeSelect,
  },
  props: {
    organizationId: {
      required: true,
    },
    closeAssetInfo: {
      type: Function,
      required: true,
    },
    onUpdata: {
      type: Function,
      required: true,
    },
    assetInfo: {
      type: Object,
    },
    // typeList: {
    //     type: Array,
    //     required: true
    // },
    buildList: {
      type: Array,
      required: true,
    },
    isAddWrite: {
      required: true,
    },
    defaultFbsId: {
      type: [String, Number],
      default: '',
    },
  },
  data() {
    return {
      newBuildList: [],
      isEdit: this.assetInfo.name ? true : false,
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
      assetInfoForm: {
        id: '',
        picturesUrls: '',
        name: '',
        status: '0',
        categoryId: '',
        fbsId: '',
        location: '',
        visualCodeType: '0',
        visualCode: '', // 手动输入二维码
        maintainCompanyType: '1',
        // maintainCompanyId: '', // 其他维保公司编码
        serialNumber: '',
        model: '',
        brand: '',
        producerName: '',
        productionTimeStr: '',
        yearNum: '', // 年限
        monthNum: '', // 月限
        dayNum: '', // 日限
        relateFcIds: [],
        remarks: '',
      },
      isContinue: true,
      assetInfoFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        categoryId: [
          { required: true, message: '请选择系统与类别', trigger: 'blur' },
        ],
        fbsId: [
          { required: true, message: '请选择所在建筑物', trigger: 'blur' },
        ],
        location: [
          { required: true, message: '请输入具体位置', trigger: 'blur' },
        ],
        visualCodeType: [
          { required: true, message: '请选择标识类型', trigger: 'change' },
        ],
        maintainCompanyType: [
          { required: true, message: '请选择维保公司', trigger: 'change' },
        ],
        // 非必填
        serialNumber: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        model: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        brand: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        producerName: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        remarks: [
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字',
            trigger: 'blur',
          },
        ],
      },
      // 消防系统-资产类别
      typeList: [],
      typeDefaultProps: {
        children: 'categoryList',
        label: 'name',
        value: 'id',
      },
      typeNodeKey: 'id',
      defaultCheckedCategoryId: [],
      // 建筑物
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      defaultCheckedFbsId: [],
      // 其他维保公司
      // maintainCompanyOptions: [],
      relateFcIdsSelectloading: false,
      relateFcOptions: [], // 关联物联设备
      relateFcPageIndex: 1,
      relateFcTotal: 0,
      // 提示选择的树节点是否正确
      isChooseTree: false,
      parentEvent: true,
      copyDialogVisible:false,
      copyNum:''
    }
  },
  created() {
    var that = this
    var arr = $.extend(true, [], that.buildList)
    //   arr[0]['disabled'] = true
    that.newBuildList = arr
    // 删除全部
    //   if(that.typeList[0].id === '') {
    //     that.typeList.shift()
    //   }
    that.getFcfOptions()
    that.getTypeList()
    // 获取token
    that.getToken()
    // 获取其他维保公司信息
    //   getAMCs({
    //     orgId: that.organizationId
    //   }).then(res => {
    //      that.maintainCompanyOptions = res.data
    //   })
    // 初始化后切换下拉框检验的触发类型
    that.$nextTick(() => {
      that.assetInfoFormRules.categoryId[0].trigger = 'change'
      this.assetInfoFormRules.fbsId[0].trigger = 'change'
      // 最顶选项禁用（恶心）
      // let $line = $('.asset-build .el-tree-node__content')
      // $($line[0]).addClass('is-disabled')
    })
  },
  methods: {
    getTypeList() {
      let that = this
      getAssetsCategoryId().then((res) => {
        if (res.status === 200) {
          let newArr = res.data
          // 系统与类别的系统节点增加disabled
          for (var i = 0, len = newArr.length; i < len; i++) {
            newArr[i].disabled = true
          }
          that.typeList = newArr
          // 是否存在历史值
          if (that.assetInfo.name) {
            that.$nextTick(() => {
              // radio类型的值要转成String类型
              that.assetInfo.status = that.assetInfo.isUse.toString()
              that.assetInfo.visualCodeType = that.assetInfo.visualCodeType.toString()
              that.assetInfo.maintainCompanyType = (
                that.assetInfo.maintainCompanyType || ''
              ).toString()
              // 设置系统与类别下拉康初始值
              that.defaultCheckedCategoryId = that.assetInfo.categoryId
                .toString()
                .split(',')
              // 设置所在建筑物下拉框初始值
              that.defaultCheckedFbsId = that.assetInfo.fbsId
                .toString()
                .split(',')
              // 设置上传图片初始值
              that.assetInfo.picturesUrls
                ? $.each(
                    that.assetInfo.picturesUrls.split(','),
                    (index, url) => {
                      that.qiniuData.fileList.push({
                        name: that.assetInfo.name + index,
                        url: url,
                      })
                    }
                  )
                : ''
              //  [{currentLabel:'2号水压传感器',  value: 2158934}, {currentLabel:'004回路002号烟感', value:2158921}]
              that.assetInfo.relateFcIds =
                that.assetInfo.relateFcIds.toString() === ''
                  ? []
                  : that.assetInfo.relateFcIds.toString().split(',')
              // 合并历史值
              for (let key in that.assetInfo) {
                for (let name in that.assetInfoForm) {
                  if (name === key) {
                    that.assetInfoForm[name] = that.assetInfo[key]
                    break
                  }
                }
              }
              // 生产日期
              that.assetInfoForm.productionTimeStr =
                that.assetInfo.productionTime
              /*
               * 解决带分页的下拉框回显值不在首页无法显示label问题
               */
              that.$nextTick(() => {
                if (that.assetInfo.relateFcNames != '') {
                  let $tags = $('#relateFcIds .el-select__tags').find(
                    '.el-select__tags-text'
                  )
                  let nameList = that.assetInfo.relateFcNames.split(',')
                  for (let i = 0, len = $tags.length; i < len; i++) {
                    $tags[i].innerText = nameList[i]
                  }
                }
                return false
              })
            })
          } else {
            this.$nextTick(() => {
              if (this.defaultFbsId) {
                this.defaultCheckedFbsId = this.defaultFbsId
                  .toString()
                  .split(',')
                this.assetInfoForm.fbsId = this.defaultFbsId
              }
            })
          }
        }
      })
    },
    getFcfOptions(name, pageChange) {
      let that = this
      // 重新搜索时页码复原
      if (!pageChange) {
        this.relateFcPageIndex = 1
      }
      let parames = {
        fbsId: 0,
        organizationId: this.organizationId,
        parentId: 0,
        pageIndex: this.relateFcPageIndex - 1,
        pageSize: 10,
        name: name || '',
      }
      that.relateFcIdsSelectloading = true
      // 获取关联物联设备
      getFcfSelectList(parames).then((res) => {
        that.relateFcOptions = res.data
        that.relateFcTotal = res.total
        that.relateFcIdsSelectloading = false
      })
    },
    handleCurrentChange(currentpage) {
      this.relateFcPageIndex = currentpage
      this.getFcfOptions($('#relateFcIds .el-select__input').val(), true)
    },
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
      })
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.qiniuData.fileList = fileList
    },
    handleRemovePic: function (file, fileList) {
      //删除成功
      this.qiniuData.fileList = fileList
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
    },
    handleExceed(files, fileList) {
      //文件超出个数限制时的钩子
      this.$message.warning(`只能上传一张图片！`)
    },
    // 点击树节点
    handleNodeClick(val) {
      let _this = this
      if (val.type == 4 || val.type == 5) {
        _this.isChooseTree = false
      } else {
        _this.isChooseTree = true
      }
    },
    // 保存
    saveAsset(formName, type) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid && !that.isChooseTree) {
          let parames = that.assetInfoForm
          parames.picturesUrls = util.ilinkArrHandle
            .getqiniuPicUrlArr(that.qiniuData.fileList)
            .toString()
          parames.account = that.$store.state.userinfo.accountName
          parames.organizationId = that.organizationId
          this.formData={
            ...parames,
            relateFcIds:parames.relateFcIds.join(',')
          }
          if(type==3){
            this.showCopyDialog()
          }else{
            that.isContinue = false
            this.requestSave({
              ...parames,
              relateFcIds:parames.relateFcIds.join(',')
            },type)
          }
        } else {
          return false
        }
      })
    },
    showCopyDialog(){
      this.copyDialogVisible=true
    },
    confirmCopy(){
      let assetsInfos=[this.formData]
      for(let i=1;i<this.copyNum;i++){
        assetsInfos.push({
          ...this.formData,
        })
      }
      batchSaveAssetsInfo({assetsInfos}).then(res=>{
        if(res.status===200){
          this.copyDialogVisible=false
          this.$message({
            message: '保存成功！',
            type: 'success',
          })
          if(this.assetInfoForm.name.indexOf('-已创建')<0){
            this.assetInfoForm.name+='-已创建'
          }
          this.onUpdata()
        }else{
          this.$message({
            message: res.info,
            type: 'error',
          })
        }
      })
    },
    requestSave(parames,type){
      const that=this
      // 提交
      updateAInfo(parames).then((res) => {
        that.isContinue = true
        if (res.status === 200) {
          let relateFcIdsType = typeof that.assetInfoForm.relateFcIds
          if (
            relateFcIdsType == 'string' &&
            that.assetInfoForm.relateFcIds
          ) {
            that.assetInfoForm.relateFcIds = that.assetInfoForm.relateFcIds.split(
              ','
            )
            that.assetInfoForm.name = that.assetInfoForm.name + '-复制'
            for (
              let i = 0;
              i < that.assetInfoForm.relateFcIds.length;
              i++
            ) {
              that.assetInfoForm.relateFcIds[i] = parseInt(
                that.assetInfoForm.relateFcIds[i]
              )
            }
          } else if (
            relateFcIdsType == 'string' &&
            !that.assetInfoForm.relateFcIds
          ) {
            that.assetInfoForm.relateFcIds = []
            that.assetInfoForm.name = that.assetInfoForm.name + '-复制'
          }

          if (type == 1) {
            that.closeAssetInfo(true)
          } else {
            that.onUpdata()
            setTimeout(function () {
              that.$emit('child-event', that.parentEvent)
            }, 500)
          }

          that.$message({
            message: '保存成功！',
            type: 'success',
          })
        } else {
          let relateFcIdsType = typeof that.assetInfoForm.relateFcIds
          if (
            relateFcIdsType == 'string' &&
            that.assetInfoForm.relateFcIds
          ) {
            that.assetInfoForm.relateFcIds = that.assetInfoForm.relateFcIds.split(
              ','
            )
            that.assetInfoForm.name = that.assetInfoForm.name + '-复制'
            for (
              let i = 0;
              i < that.assetInfoForm.relateFcIds.length;
              i++
            ) {
              that.assetInfoForm.relateFcIds[i] = parseInt(
                that.assetInfoForm.relateFcIds[i]
              )
            }
          }
          that.$message({
            message: res.info,
            type: 'warning',
          })
        }
      })
    },
  },
}
</script>
<style>
.add-property-detail .asset-info-form .el-form-item {
  margin-bottom: 15px;
}
.asset-info-form .el-form--label-top .el-form-item__label {
  padding: 0;
}
</style>
